package com.hcb.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.adapter.AdapterResponderList;
import com.hcb.adapter.AdapterYourContact;
import com.hcb.app911.MainActivity;
import com.hcb.app911.R;
import com.hcb.constants.Constants;
import com.hcb.dto.CustomerDTO;
import com.hcb.dto.ResponderDTO;
import com.hcb.dto.ResponderListDTO;
import com.hcb.model.utils.CustomerModel;
import com.hcb.webservice.InternetUtils;
import com.hcb.webservice.ServiceHandler;

import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AlertSentFragment extends Fragment implements OnClickListener {
	Button btnSentAlert;
	ListView lvOurContact;
	AdapterResponderList adapter;
	ArrayList<Object> arrData;
	ArrayList<Object> arrData1;
	AdapterYourContact adapter1;
	TextView txtYourName1, txtYourName2, txtStyle, strText;
	String yourName1 = "", yourName2 = "";
	String alert_id;
	String strtextview = "If you have some time and are able to, kindly provide more information about your emergency and we will update the alerts";
	ImageView imgyour1, imgyour2;
	int key_center = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_alert_sent,
				container, false);
		((MainActivity)this.getActivity()).getImgDetail().setImageResource(R.drawable.mydetail);
		((MainActivity)this.getActivity()).getImgHome().setImageResource(R.drawable.icon);
		btnSentAlert = (Button) rootView.findViewById(R.id.btnSentAlert);
		lvOurContact = (ListView) rootView.findViewById(R.id.lvOurContact);
		txtYourName1 = (TextView) rootView.findViewById(R.id.txtYourName1);
		txtYourName2 = (TextView) rootView.findViewById(R.id.txtYourName2);
		txtStyle = (TextView) rootView.findViewById(R.id.txtStyle);
		strText = (TextView) rootView.findViewById(R.id.strText);
		strText.setText(strtextview);
		imgyour1 = (ImageView) rootView.findViewById(R.id.imgyour1);
		imgyour2 = (ImageView) rootView.findViewById(R.id.imgyour2);
		Bundle data = getArguments();
		ResponderListDTO responderlist = (ResponderListDTO) data
				.getSerializable("data");
		ArrayList<ResponderDTO> list = responderlist.getParliaments();

		// Bundle data = getIntent().getExtras();

		String style = data.getString("style");
		alert_id = data.getString("alert_id");
		key_center = data.getInt("key_center");
		if (!style.equalsIgnoreCase("")) {
			txtStyle.setText("<<" + style + ">>");
		}
		arrData = new ArrayList<Object>();
		arrData1 = new ArrayList<Object>();
		for (ResponderDTO responderDTO : list) {
			arrData.add(responderDTO);

		}
		adapter = new AdapterResponderList(getActivity(),
				R.layout.adapter_responder_list, arrData);
		lvOurContact.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		// adapter1 = new AdapterYourContact(this,
		// R.layout.adapter_responder_list, arrData1);
		// lvYourContact.setAdapter(adapter1);

		CustomerModel model = CustomerModel.getInstance();
		CustomerDTO dto = model.getCustomer(getActivity());
		new VerySlowTask(dto).execute();
		btnSentAlert.setOnClickListener(this);
		return rootView;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btnSentAlert:
			if (InternetUtils.getInstance().isConnectingToInternet(
					getActivity())) {

				UpdateAlertFragment fragment = new UpdateAlertFragment();
				FragmentManager fragmentManager = getActivity()
						.getSupportFragmentManager();
				FragmentTransaction ft = fragmentManager.beginTransaction();
				Bundle bundle = new Bundle();
				bundle.putString("alert_id", alert_id);
				if (fragment != null) {
					fragment.setArguments(bundle);
					ft.remove(fragment);
					ft.replace(R.id.frame_container, fragment);
					ft.commit();
				}

				// btnSentAlert.setBackgroundResource(R.drawable.updatealertf);
				// Intent intent = new Intent(this, UpdateAlertActivity.class);
				// intent.putExtra("alert_id", alert_id);
				// startActivity(intent);
			} else {
				Toast.makeText(getActivity(),
						"No network please connect network", Toast.LENGTH_LONG)
						.show();
			}

			break;

		default:
			break;
		}

	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		String result;
		CustomerDTO customer;
		JSONObject data_body = null;
		boolean flag = false;
		String name1 = "";

		public VerySlowTask(CustomerDTO cus) {
			customer = cus;
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.GET_CUSTOMER_DETAILS));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair(Constants.CUSTOMER_ID,
					customer.getCustomer_id()));
			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject object;
					object = new JSONObject(jsonStr);
					String value = object.getString("result");
					data_body = object.getJSONObject("data_body");
					if (!data_body.equals(null)) {

						if (value.contains("success")) {
							CustomerDTO dto = new CustomerDTO();

							String name1 = data_body
									.getString("nominated_conact_name_one");
							String name2 = data_body
									.getString("nominated_conact_name_two");
							if (!name1.equalsIgnoreCase("")) {
								dto.setNominated_conact_name_one(name1);

							}
							if (!name2.equalsIgnoreCase("")) {
								dto.setNominated_conact_name_two(name2);
							}
							yourName1 = dto.getNominated_conact_name_one();
							yourName2 = dto.getNominated_conact_name_two();

						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			txtYourName1.setText(yourName1);
			txtYourName2.setText(yourName2);
			if (!txtYourName1.getText().toString().equalsIgnoreCase("")) {
				imgyour1.setBackgroundResource(R.drawable.iconcheck);
			}
			if (!txtYourName2.getText().toString().equalsIgnoreCase("")) {
				imgyour2.setBackgroundResource(R.drawable.iconcheck);
			}
			if (key_center != 1) {
				if (txtYourName1.getText().toString().equalsIgnoreCase("")
						&& txtYourName2.getText().toString()
								.equalsIgnoreCase("")) {
					final Dialog center_err = new Dialog(getActivity(),
							android.R.style.Theme_Translucent);
					center_err.requestWindowFeature(Window.FEATURE_NO_TITLE);
					center_err.setCancelable(true);
					center_err.setContentView(R.layout.dialog_center_err);
					TextView tvtitle_err = (TextView) center_err
							.findViewById(R.id.tvtitle_err);
					TextView tvContent_err = (TextView) center_err
							.findViewById(R.id.tvContent_err);
					tvtitle_err.setText("don't find contacts");
					tvContent_err.setText("Do you want add contacts?");
					Button btnyes = (Button) center_err
							.findViewById(R.id.btnyes);
					Button btnno = (Button) center_err.findViewById(R.id.btnno);

					btnyes.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							EmergencyContactsFragment fragment = new EmergencyContactsFragment();
							FragmentManager fragmentManager = getActivity()
									.getSupportFragmentManager();
							FragmentTransaction ft = fragmentManager
									.beginTransaction();
							if (fragment != null) {
								ft.remove(fragment);
								ft.replace(R.id.frame_container, fragment);
								ft.commit();
							}
							center_err.dismiss();
						}
					});
					btnno.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							HomeFragment fragment = new HomeFragment();
							FragmentManager fragmentManager = getActivity()
									.getSupportFragmentManager();
							FragmentTransaction ft = fragmentManager
									.beginTransaction();
							if (fragment != null) {
								ft.remove(fragment);
								ft.replace(R.id.frame_container, fragment);
								ft.commit();
							}
							center_err.dismiss();

						}
					});

					center_err.show();
				}
			}

		}

	}
}
